package com.candy.candyproduct.config.weightBalance;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/8/17 9:52
 * @Description 描述
 */
@Slf4j
public class WeightBalanceConfig extends AbstractLoadBalancerRule {

    @Autowired
    private NacosServiceManager nacosServiceManager;

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    private static AtomicInteger COUNT = new AtomicInteger(0);

    public WeightBalanceConfig() {
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        try {
            // 1、获取当前服务的分组名称
            String groupName = nacosDiscoveryProperties.getGroup();
            // 2、获取当前服务的负载均衡器
            BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            // 3、获取目标服务的服务名
            String serviceName = baseLoadBalancer.getName();
            // 4、获取nacos提供的服务注册api
            NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
            // 5、根据目标服务名称和分组名称去获取服务实例，nacos实现了权重的负载均衡算法  false: 及时获取nacos注册服务信息
            List<Instance> allInstances = namingService.getAllInstances(serviceName, groupName, false);
            Instance instance = WeightedBalancer.chooseInstanceByRandomWeight(allInstances, nacosDiscoveryProperties.getClusterName());
            // 请求总数
            COUNT.incrementAndGet();
            log.info("路由的请求总数: {}。", COUNT.intValue());
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error("自定义负载均衡策略-权重 调用异常: ", e);
            return null;
        }
    }

}
